import sqlalchemy
from sqlalchemy.orm import sessionmaker

# 我将之前成功获取的数据库URI硬编码在这里，以确保脚本能独立运行
DATABASE_URI = "mysql+pymysql://user_weixin:EICWzF64QdD9G7a4@127.0.0.1:3306/weixin?charset=utf8mb4"

def clear_tables():
    """连接到数据库并清空指定的表"""
    try:
        engine = sqlalchemy.create_engine(DATABASE_URI)
        Session = sessionmaker(bind=engine)
        session = Session()

        tables_to_clear = [
            'payments',
            'activity_participants',
            'orders',
            'activities'
        ]

        print("开始清理数据库测试数据...")

        session.execute(sqlalchemy.text("SET FOREIGN_KEY_CHECKS = 0;"))
        print("  - 临时关闭外键约束。")

        for table in tables_to_clear:
            try:
                session.execute(sqlalchemy.text(f"TRUNCATE TABLE {table};"))
                print(f"  - 成功清空表: {table}")
            except Exception as e:
                print(f"  - 清空表 {table} 时发生错误: {e}")
                session.rollback()

        session.execute(sqlalchemy.text("SET FOREIGN_KEY_CHECKS = 1;"))
        print("  - 重新开启外键约束。")

        session.commit()
        print("\\n数据库清理完成！")

    except Exception as e:
        print(f"连接数据库或执行清理时发生严重错误: {e}")
    finally:
        if 'session' in locals() and session.is_active:
            session.close()

if __name__ == '__main__':
    clear_tables()
